package com.example.demo.project.mpsample.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.framework.entity.R;
import com.example.demo.project.mpsample.entity.SysUserEntity;
import com.example.demo.project.mpsample.service.ISysUserService;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@AllArgsConstructor
@RestController
@RequestMapping("/user")
public class MpTestController {

    /**
     * 构造函数中会注入bean
     * // @Autowired
     */
    private ISysUserService userService;

    /**
     * 列表
     */
    @GetMapping("/list")
    public R list() {
        List<SysUserEntity> list = userService.list();
        return R.ok().data(list);
    }

    /**
     * 分页
     */
    @GetMapping("/page")
    public R page(@RequestParam(value = "p", required = false, defaultValue = "1") Integer pageIndex, @RequestParam(value = "s", required = false, defaultValue = "15") Integer pageSize) {
        IPage<SysUserEntity> page = userService.page(new Page<>(pageIndex, pageSize), null);
        return R.ok().data(page);
    }

    /**
     * 根据id获取详情
     */
    @GetMapping(value = "/{id}")
    public R detail(@PathVariable Long id) {
        return R.ok().data(userService.getById(id));
    }

    /**
     * 新增/添加
     */
    // @RepeatSubmit
    @PostMapping
    public R add(@Validated @RequestBody SysUserEntity entity) {
        boolean result = userService.save(entity);
        return result ? R.ok() : R.error();
    }

    /**
     * 修改/更新
     */
    @PutMapping
    public R edit(@Validated @RequestBody SysUserEntity entity) {
        boolean result = userService.updateById(entity);
        return result ? R.ok() : R.error();
    }

    /**
     * 删除1-n个
     * <p>
     * eg:
     * xxx/1
     * xxx/1,2,3
     */
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable Long[] ids) {
        boolean result = userService.removeByIds(CollUtil.newArrayList(ids));
        return result ? R.ok() : R.error();
    }

}
